package com.ironman.sailboat.mobile.computer.v2;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

/**
 * 1.3
 */
public class ThresholdFilter {

    private Double currentValue;

    private final double valThreshold;

    private final int countThreshold;

    private final AtomicInteger countThresholdLauncher;

    public ThresholdFilter(Double valThreshold, int countThreshold) {
        this.valThreshold = valThreshold;
        this.countThreshold = countThreshold;
        this.countThresholdLauncher = new AtomicInteger(this.countThreshold);
    }

    public void filterVal(Double newVal, Consumer<Double> consumer) {
        if (this.currentValue == null) {
            this.currentValue = newVal;
        } else {
            if (Objects.nonNull(newVal)) {
                if (Math.abs(newVal - currentValue) >= valThreshold) {
                    this.countThresholdLauncher.set(this.countThreshold);
                    this.currentValue = newVal;
                } else {
                    if (this.countThresholdLauncher.decrementAndGet() == 0) {
                        this.countThresholdLauncher.set(this.countThreshold);
                        this.currentValue = newVal;
                    }
                }
            } else {
                this.currentValue = null;
            }
        }
        consumer.accept(this.currentValue);
    }
}
